package com.frxuexi.mdm2206.myview

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.view.marginLeft
import com.frxuexi.mdm2206.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask
import kotlin.random.Random

class MyHBView:RelativeLayout {

    lateinit var timer: Timer
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)


    fun start(){
        timer= Timer()
        GlobalScope.launch {
            timer.schedule(timerTask {
                val imageView = ImageView(context)
                imageView.setImageResource(com.frxuexi.lib_base.R.drawable.hb)
                val params = LayoutParams(150,200)
                val num = Random.nextInt(0, 1000)
                params.leftMargin=num
                params.topMargin=0
                imageView.layoutParams=params

                GlobalScope.launch(Dispatchers.Main) {
                    addView(imageView)
                    val animator = ObjectAnimator.ofFloat(imageView,"translationY",0f, 1800f)
                    animator.setDuration(5000)
                    animator.start()
                }
            },0,200)
        }

    }

    fun stop(){
        timer.cancel()
    }
}